package com.phpxiu.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.phpxiu.app.adapter.C2CListAdapter;
import com.phpxiu.app.adapter.holder.C2CListViewHolder;
import com.phpxiu.app.api.callback.MsgCountManager;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.event.OnBlockEvent;
import com.phpxiu.app.model.list.C2CConversation;
import com.phpxiu.app.presenters.C2CManagerPresenter;
import com.phpxiu.app.presenters.viewinterface.C2CManagerView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.ListEmptyView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.dialog.C2CListOperaMenus;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;
import com.tencent.TIMRefreshListener;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by 吴金洲 on 2016/7/27
 */
public class C2CConversationManager extends UIBase implements C2CManagerView,
        TIMMessageListener,
        TIMRefreshListener,
        View.OnClickListener,
        AdapterView.OnItemClickListener,
        AbsListView.OnItemLongClickListener,
        C2CListOperaMenus.C2CListMenusOptionsCallBack {
    public final static String TAG="C2CConversationList";
    private final static int HANDLE_ADD_NEW_CONVERSATION=0x1;
    private final static int HANDLE_REMOVE_CONVERSATION=0x2;
    private WindowLayout mainView;
    private C2CManagerPresenter mPresenter;
    private ListView mListView;
    private ListEmptyView emptyView;
    private C2CListAdapter mAdapter;
    private List<C2CConversation>conversations=new ArrayList<C2CConversation>();//已拷贝后台用户资的会话列表
    private C2CListOperaMenus optionsMenu;
    private boolean isRefreshMsgCount=false;//退出界面时刷新未读数
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isRefreshMsgCount=false;
        setContentView(R.layout.c2c_conversation_manager);
        mainView=(WindowLayout)findViewById(R.id.root_view);
        EventBus.getDefault().register(this);
        mPresenter=new C2CManagerPresenter(this);
        init();
    }

    /**
     * 初始化会话列表界面
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        mListView=(ListView)findViewById(R.id.c2c_conversation_list_view);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        emptyView=new ListEmptyView(this);
        emptyView.setMsg(getString(R.string.list_empty_title));
        mListView.setDivider(null);
        mAdapter=new C2CListAdapter(this,conversations);
        mListView.setEmptyView(emptyView);
        mListView.setAdapter(mAdapter);
        emptyView.loaded();
        TIMManager.getInstance().setRefreshLiistener(this);
        TIMManager.getInstance().addMessageListener(this);
        mPresenter.loadTIMConversation();//加载会话列表
        findViewById(R.id.title).setOnClickListener(this);
        mainView.showTopMsg(getString(R.string.long_click_delete));
    }

    /**
     * 初始化列表操作菜单
     */
    private void initOptionMenu(){
        optionsMenu=new C2CListOperaMenus(this);
        optionsMenu.setDeleteCallBack(this);
        optionsMenu.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
    }

    @Override
    public void refresh(Map<String, C2CConversation> conversationMap) {
        conversations.clear();
        Set<String>peers=conversationMap.keySet();
        for (String peer:peers){
            C2CConversation c=conversationMap.get(peer);
            if(c.getSender()!=null){
                conversations.add(c);
            }
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                for (C2CConversation c:conversations){
                    if(c.getLastMessage()==null){
                        TIMConversation tc=c.getConversation();
                        try {
                            c.setLastMessage(tc.getLastMsgs(1).get(0));
                        }catch (NullPointerException e){
                            CrashReport.postCatchedException(e);
                        }catch (IndexOutOfBoundsException e){

                        }
                    }
                }
                mAdapter.notifyDataSetChanged();

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.title:
                //Intent chat=new Intent(this, C2CChat.class);
                //chat.putExtra(C2CChat.EXTRA_CONVERSATION_ID, "10009");
                //startActivity(chat);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (view.getTag()!=null&&view.getTag() instanceof C2CListViewHolder){
            try {
                C2CConversation c=((C2CListViewHolder)view.getTag()).getC2CConversation();
                gotoChat(c.getPeer(),c.getSender().getUid(),c.getNick(),c.getAvatar());
                c.readAllMessage();
                mAdapter.notifyDataSetChanged();
            }catch (NullPointerException e){
                CrashReport.postCatchedException(e);
            }catch (ClassCastException e){
                CrashReport.postCatchedException(e);
            }
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (view.getTag()!=null&&view.getTag() instanceof C2CListViewHolder){
            try {
                C2CConversation c=((C2CListViewHolder)view.getTag()).getC2CConversation();
                if(optionsMenu==null){
                    initOptionMenu();
                }
                optionsMenu.show(c.getPeer());
            }catch (NullPointerException e){
                CrashReport.postCatchedException(e);
            }catch (ClassCastException e){
                CrashReport.postCatchedException(e);
            }
        }
        return true;
    }

    /**
     * 跳转到聊天界面
     * @param peer
     * @param uid
     * @param nick
     * @param avatar
     */
    @Override
    public void gotoChat(String peer,String uid,String nick,String avatar){
        Intent chat=new Intent(this, C2CChat.class);
        chat.putExtra(C2CChat.EXTRA_CONVERSATION_ID, peer);
        chat.putExtra(C2CChat.EXTRA_USER_ID, uid);
        chat.putExtra(C2CChat.EXTRA_USER_NICK_NAME,nick);
        chat.putExtra(C2CChat.EXTRA_USER_AVATAR,avatar);
        startActivity(chat);
    }

    @Override
    public void onDeleteConversation(String peer) {
        mPresenter.deleteConversation(peer);
        isRefreshMsgCount=true;//退出界面时刷新未读数
    }

    @Override
    public void onErr(String s) {

    }

    @Override
    public void finish() {
        if(isRefreshMsgCount){
            isRefreshMsgCount=false;
            MsgCountManager.getInstance().refreshMsgCount();
        }
        handler.removeCallbacksAndMessages(null);
        super.finish();
    }

    /**
     * 销毁
     */
    @Override
    public void onDestroy(){
        if(mPresenter!=null){
            mPresenter.onDestroy();
        }
        TIMManager.getInstance().setRefreshLiistener(null);
        TIMManager.getInstance().removeMessageListener(this);
        if(isRefreshMsgCount){
            isRefreshMsgCount=false;
            MsgCountManager.getInstance().refreshMsgCount();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 会话刷新
     */
    @Override
    public void onRefresh() {
        //TODO SOMETHING
    }

    /**
     * 会话刷新，多终端同步数据
     * @param timConversations
     */
    @Override
    public void onRefreshConversation(List<TIMConversation> timConversations) {
        //TODO SOMETHING
    }

    /**
     * https://www.qcloud.com/doc/product/269/1561
     * ，默认情况下所有消息监听器都将按添加顺序被回调一次
     * 除非用户在OnNewMessages回调中返回true，此时将不再继续回调下一个消息监听器。
     * @param list
     * @return
     */
    @Override
    public boolean onNewMessages(List<TIMMessage> list) {
        Message msg=handler.obtainMessage();
        for (TIMMessage item:list){
            if(item.getConversation().getType()==TIMConversationType.C2C){
                if(!Constants.SERVER_ADMIN_ID.equals(item.getConversation().getPeer())) {//忽略管理员会话
                    msg.what=HANDLE_ADD_NEW_CONVERSATION;
                    msg.obj=item;
                    handler.sendMessage(msg);
                }
            }
        }
        return false;
    }

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what){
            case HANDLE_ADD_NEW_CONVERSATION:
                TIMMessage message=(TIMMessage)msg.obj;
                mPresenter.addNewConversation(message);
                break;
            case HANDLE_REMOVE_CONVERSATION://删除会话
                try {
                    String peer=msg.obj.toString();
                    removeConversation(peer);
                }catch (NullPointerException e){
                    CrashReport.postCatchedException(e);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 移除会话
     * @param peer
     */
    private void removeConversation(String peer){
        if(peer==null){
            return;
        }
        for (C2CConversation c:conversations){
            if(c.getPeer().equals(peer)){
                TIMManager.getInstance().deleteConversation(TIMConversationType.C2C,peer);
                conversations.remove(c);
                mAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 拉黑事件
     */
    @Subscribe
    public void onBlock(OnBlockEvent event){
        KKYUtil.log(TAG + "->会话列表的" + event.getPeer() + "被拉黑");
        Message message=handler.obtainMessage();
        message.what=HANDLE_REMOVE_CONVERSATION;
        message.obj=event.getPeer();
        handler.sendMessage(message);
        isRefreshMsgCount=true;
    }
}
